<template>
  <el-form
    v-if="getShow"
    :rules="rules"
    ref="formEnrollLogin"
    :model="enrollForm"
    class="login-form w-full"
    label-position="top"
    label-width="80px"
    size="large"
  >
    <h2 class="enter-x mb-3 text-center text-2xl font-bold xl:text-center xl:text-3xl">
      <span class="cursor-pointer" @click="changeType = 0" :class="changeType == 0 ? 'active' : ''"
        >用户注册</span
      >
      <span
        class="ml-20px cursor-pointer"
        @click="changeType = 1"
        :class="changeType == 1 ? 'active' : ''"
        >企业注册</span
      >
    </h2>

    <el-row style="margin-right: -10px; margin-left: -10px">
      <div class="w-full pt-10px">
        <el-col :span="24" v-if="changeType == 0">
          <el-form-item label="姓名" prop="name">
            <el-input v-model.trim="enrollForm.name" placeholder="请输入姓名" link type="primary" />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="changeType == 0">
          <el-form-item label="联系方式" prop="contactMobile">
            <el-input
              v-model.trim="enrollForm.contactMobile"
              placeholder="该手机号将作为登录账号使用"
            />
          </el-form-item>
        </el-col>
        <el-form-item class="!mb-12px" v-if="changeType == 1" label="企业名称" prop="name">
          <el-input v-model.trim="enrollForm.name" placeholder="请输入企业名称(最少4位)" />
        </el-form-item>
        <el-form-item class="!mb-12px" v-if="changeType == 1" label="企业法人" prop="contactName">
          <el-input v-model.trim="enrollForm.contactName" placeholder="请输入企业法人" />
        </el-form-item>
        <el-form-item class="!mb-12px" v-if="changeType == 1" label="联系方式" prop="contactMobile">
          <el-input
            v-model.trim="enrollForm.contactMobile"
            placeholder="需方便接通电话以确认身份信息"
          />
        </el-form-item>
        <el-form-item class="!mb-12px" v-if="changeType == 1" label="登录账号" prop="username">
          <el-input v-model.trim="enrollForm.username" placeholder="请设置登录账号" />
        </el-form-item>
        <el-form-item class="!mb-12px" v-if="changeType == 1" label="登录密码" prop="password">
          <el-input
            v-model.trim="enrollForm.password"
            type="password"
            show-password
            placeholder="请设置登录密码"
          />
        </el-form-item>
        <!-- 验证码 -->
        <el-col :span="24">
          <el-form-item
            label="验证码"
            :class="changeType == 1 ? '!mb-12px' : ''"
            prop="code"
            class="codeStyle"
          >
            <el-row :gutter="5" justify="space-between" style="width: 100%">
              <el-col :span="24">
                <el-input
                  v-model.trim="enrollForm.code"
                  :placeholder="t('login.codePlaceholder')"
                  :prefix-icon="iconCircleCheck"
                  class="codeInput"
                >
                  <template #append>
                    <span
                      v-if="mobileCodeTimer <= 0"
                      class="text-#172b4d"
                      style="cursor: pointer"
                      @click="getCode"
                    >
                      {{ t('login.getSmsCode') }}
                    </span>
                    <span v-if="mobileCodeTimer > 0" style="cursor: pointer">
                      {{ mobileCodeTimer }}秒后可重新获取
                    </span>
                  </template>
                </el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <!-- 注册 / 返回按钮 -->
        <el-col :span="24">
          <el-form-item class="btnml_0" :class="changeType == 1 ? '!mb-12px' : ''">
            <XButton
              :loading="loading"
              :title="t('login.register')"
              class="w-[100%]"
              type="primary"
              @click="loginRegister()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="btnml_0" :class="changeType == 1 ? '!mb-12px' : ''">
            <XButton
              :loading="loginLoading"
              title="已有账号登录"
              class="w-[100%]"
              @click="handleBackLogin()"
            />
          </el-form-item>
        </el-col>
        <Verify
          ref="verify"
          :captchaType="captchaType"
          :imgSize="{ width: '400px', height: '200px' }"
          mode="pop"
          @success="getSmsCode"
        />
      </div>
    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import { sendSmsCode, userRegister, entRegister } from '@/api/login'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useLoginState } from './useLogin'
import { setTenantId, setTenantSign, setToken } from '@/utils/auth'
defineOptions({ name: 'RegisterForm' })
const props = defineProps({
  agree: {
    type: Boolean,
    default: () => true
  }
})
const { t } = useI18n()
const message = useMessage()
const loginLoading = ref(false)
const { handleBackLogin, getLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER)

const rules = {
  name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
  contactName: [{ required: true, message: '请输入企业法人', trigger: 'blur' }],
  username: [{ required: true, message: '请输入登录账户', trigger: 'blur' }],
  password: [{ required: true, message: '请输设置登录密码', trigger: 'blur' }],
  contactMobile: [
    { required: true, message: t('sys.login.loginNumberPlaceholder'), trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: t('profile.rules.truephone'),
      trigger: 'blur'
    },
    { max: 11, message: '限制长度11位', trigger: 'blur' }
  ],
  code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
}

const enrollForm = reactive({
  name: '',
  contactMobile: '',
  code: '',
  contactName: '',
  username: '',
  password: ''
})

const smsVO = reactive({
  smsCode: {
    scene: 22
  }
})

const isShowCode = ref(false)

const changeType = ref(0)

const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
// 获取验证码
const getCode = async () => {
  if (!props.agree) {
    message.error('请先同意用户使用协议和个人信息保护政策')
    return
  }
  verify.value.show()
}
const mobileCodeTimer = ref(0)
/** 发送验证码 */
const getSmsCode = async () => {
  smsVO.smsCode.mobile = enrollForm.contactMobile
  await sendSmsCode(smsVO.smsCode).then(async () => {
    message.success(t('login.SmsSendMsg'))
    // 设置倒计时
    mobileCodeTimer.value = 60
    let msgTimer = setInterval(() => {
      mobileCodeTimer.value = mobileCodeTimer.value - 1
      if (mobileCodeTimer.value <= 0) {
        clearInterval(msgTimer)
      }
    }, 1000)
  })
}
const { push } = useRouter()
/**注册 */
const formEnrollLogin = ref()
const loginRegister = async () => {
  if (!props.agree) {
    message.error('请先同意用户使用协议和个人信息保护政策')
    return
  }
  // 校验表单
  if (!formEnrollLogin) return
  const valid = await formEnrollLogin.value.validate()
  if (!valid) return
  try {
    if (changeType.value == 0) {
      const obj = {
        name: enrollForm.name,
        authType: 2,
        contactMobile: enrollForm.contactMobile,
        code: enrollForm.code
      }
      const resp = await userRegister(obj)
      setTenantId(resp.tenantId)
      setTenantSign(resp.sign)
      setToken(resp)
      push({ path: '/' })
    } else {
      const res = await entRegister(enrollForm)
      if (res) {
        enrollForm.name = ''
        enrollForm.contactMobile = ''
        enrollForm.code = ''
        enrollForm.contactName = ''
        enrollForm.username = ''
        enrollForm.password = ''
        ElMessage.success('注册成功,请返回登录!')
        handleBackLogin()
      }
    }
  } finally {
  }
}

const passType = ref<'password' | 'text'>('text')
onMounted(() => {
  setTimeout(() => {
    passType.value = 'password'
  }, 400)
})
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.smsbtn {
  margin-top: 33px;
}

.enterIcon {
  background: none;
  text-transform: uppercase;
  font-weight: bold;
  position: relative;
  outline: none;
  box-sizing: border-box;
}

.enterIcon::before,
.enterIcon::after {
  box-sizing: inherit;
  position: absolute;
  content: '';
  border: 2px solid transparent;
  width: 0;
  height: 0;
}

.enterIcon::after {
  bottom: 0;
  right: 0;
}

.enterIcon::before {
  top: 0;
  left: 0;
}

.enterIcon:hover {
  box-shadow: var(--el-box-shadow-light);
  // span {
  //   color: var(--el-color-primary);
  // }
}

.enterIcon:hover::before,
.enterIcon:hover::after {
  width: 100%;
  height: 100%;
}

.enterIcon:hover::before {
  border-top-color: var(--el-color-primary);
  border-right-color: var(--el-color-primary);
  transition:
    width 0.3s ease-out,
    height 0.3s ease-out 0.3s;
}

.enterIcon:hover::after {
  border-bottom-color: var(--el-color-primary);
  border-left-color: var(--el-color-primary);
  transition:
    border-color 0s ease-out 0.6s,
    width 0.3s ease-out 0.6s,
    height 0.3s ease-out 1s;
}
.disabledCard {
  color: #a8abb2;
  cursor: not-allowed;
  p {
    color: #a8abb2;
  }
}

:deep(.el-input-group__append) {
  border-radius: 40px !important;
}
:deep(.el-input__wrapper) {
  border-radius: 40px !important;
}
.scrollbarHeight {
  height: 600px;
}
@media screen and (min-width: 375px) and (max-width: 450px) {
  .login_btn {
    margin-bottom: 6px;
    margin-top: 6px;
  }
  .codeStyle {
    .codeInput {
      flex-direction: column;
      :deep(.el-input__wrapper) {
        margin-bottom: 4px;
      }
    }
  }
  .scrollbarHeight {
    height: 458px;
  }
}
::v-deep .btnml_0 {
  .el-form-item__content {
    margin-left: 0 !important;
  }
}
.active {
  color: #5b83fd;
  position: relative;
  &::after {
    content: '';
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: -10px;
    width: 140px;
    height: 2px;
    background: #5b83fd;
  }
}
</style>
